package com.xiaoxu.intranetweb.mybatisplusSzappdb.controller.finance;

import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.fastjson.JSONObject;
import java.net.URLEncoder;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.business.finance.BalanceEnquiryBu;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.dao.UserInfoDao;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.excelEntity.BalanceEnquiryExcelEn;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.excelEntity.RechargeRecordExcelEn;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.excelEntity.RechargeRecordExcelEn;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.excelEntity.TruckExcelEn;
import com.xiaoxu.intranetweb.util.PermissionCheck;
import com.xiaoxu.intranetweb.util.SzResult;
import com.xiaoxu.intranetweb.util.WebFunctionUtil;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Future;

/**
 * 余额查询控制器
 *
 * @author xiaoxu
 * @version 1.0
 * @date 2022/1/5 15:00
 * @since 1.0
 */
@RestController
@RequestMapping(value = "/BalanceEnquiry")
public class BalanceEnquiryController {
    @Autowired
    private BalanceEnquiryBu balanceEnquiryBu;
    @Autowired
    private UserInfoDao userInfoDao;
    @Autowired
    private WebFunctionUtil webFunctionUtil;

    /**
     * 根据客户名称查询余额
     *
     * @param co 客户名称
     *           startTime 开始时间
     *           endTime 结束时间
     *           方法作用：根据客户名称查询余额，根据startTime和endTime查询时间段内的余额
     * @return com.xiaoxu.intranetweb.util.SzResult
     * @author xiaoxu
     * @date 2022/1/5 15:00
     * @version 1.0
     * @since 1.0
     */
    @GetMapping("/getBalanceEnquiry")
    public SzResult getBalanceEnquiry(
            @RequestParam(value = "co", required = false) String co,
            @RequestParam(value = "chiCo", required = false) String chiCo,
            @RequestParam(value = "startTime", required = false) String startTime,
            @RequestParam(value = "endTime", required = false) String endTime, HttpServletRequest request) throws Exception {
        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");
        return balanceEnquiryBu.getBalanceEnquiry(co, chiCo, startTime, endTime, token, plantId);
    }

    /**
     * 获取充值记录
     *
     * @param page      页码
     * @param pageSize  每页条数
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @param co        客户名称
     * @return com.xiaoxu.intranetweb.util.SzResult
     */
    @GetMapping("/getRechargeRecord")
    public SzResult getRechargeRecord(
            @RequestParam(value = "page", required = false) String page,
            @RequestParam(value = "pageSize", required = false) String pageSize,
            @RequestParam(value = "startTime", required = false) String startTime,
            @RequestParam(value = "endTime", required = false) String endTime,
            @RequestParam(value = "co", required = false) String co,
            @RequestParam(value = "chiCo", required = false) String chiCo,
            @RequestParam(value = "financeSubjectId", required = false) String financeSubjectId,
            HttpServletRequest request) throws Exception {
        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");
        return balanceEnquiryBu.getRechargeRecord(page, pageSize, startTime, endTime, co, chiCo, financeSubjectId,token, plantId);
    }

    /**
     * 新增充值记录
     *
     * @param jsonObject
     * @param request
     */
    @PostMapping("/addRechargeRecord")
    @PermissionCheck("addRechargeRecord")
    public SzResult addRechargeRecord(@RequestBody JSONObject jsonObject, HttpServletRequest request) throws Exception {
        String financeEnterCoId = jsonObject.getString("financeEnterCoId");
        String financeEnterNum = jsonObject.getString("financeEnterNum");
        String financeEnterRemark = jsonObject.getString("financeEnterRemark");
        String exchangeNo = jsonObject.getString("exchangeNo");
        String token = request.getHeader("Authorization");
        String targetCoId = jsonObject.getString("targetCoId");
        String plantId = request.getHeader("Plant-Id");
        //String pdtId = jsonObject.getString("pdtId");
//        权限
        return balanceEnquiryBu.addRechargeRecord(financeEnterCoId, targetCoId, financeEnterNum, financeEnterRemark, exchangeNo, token, plantId);
    }

    /**
     * 修改充值记录
     */
    @PostMapping("/updateRechargeRecord")
    public SzResult updateRechargeRecord(@RequestBody JSONObject jsonObject, HttpServletRequest request) throws Exception {
        String id = jsonObject.getString("id");
        String financeEnterRemark = jsonObject.getString("financeEnterRemark");
        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");
        return balanceEnquiryBu.updateRechargeRecord(id, financeEnterRemark, token,plantId);
    }

    //删除充值记录
    @GetMapping("/deleteRechargeRecord")
    public SzResult deleteRechargeRecord(@RequestParam String id,HttpServletRequest request) throws Exception {
        String plantId = request.getHeader("Plant-Id");
        String token = request.getHeader("Authorization");
        return balanceEnquiryBu.deleteRechargeRecord(id,plantId,token);
    }

    //是否通过一级审批
/*    @GetMapping("/sfnFianceApprove")
    public SzResult sfnFianceApprove(@RequestParam String id, @RequestParam String financeApproveStatus) throws Exception {
        return balanceEnquiryBu.sfnFianceApprove(id, financeApproveStatus);
    }*/

    //是否通过二级审批
 /*   @GetMapping("/sfnFianceApprove2")
    public SzResult sfnFianceApprove2(@RequestParam String id, @RequestParam String financeApprove2Status) throws Exception {
        return balanceEnquiryBu.sfnFianceApprove2(id, financeApprove2Status);
    }*/

    //是否充值成功
    @GetMapping("/sfnFianceEnter")
    public SzResult sfnFianceEnter(@RequestParam String id, @RequestParam String sfnFianceEnterStatus) throws Exception {
        return balanceEnquiryBu.sfnFianceEnter(id, sfnFianceEnterStatus);
    }


    /**
     * 充值记录设置
     */
    @GetMapping("/rechargeRecordSetting")
    @PermissionCheck("rechargeRecordSetting")
    public SzResult rechargeRecordSetting(@RequestParam String id, @RequestParam(required = false) String financeApproveStatus, @RequestParam(required = false) String financeApprove2Status, @RequestParam(required = false) String sfnFianceEnterStatus, HttpServletRequest request) throws Exception {
        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");
        return balanceEnquiryBu.rechargeRecordSetting(id, sfnFianceEnterStatus, token,plantId);
    }


    /**
     * 导出余额查询
     */
    @PostMapping("/balanceEnquiryExportExcel")
    public void balanceEnquiryExportExcel(@RequestBody JSONObject jsonParam, HttpServletResponse response, HttpServletRequest request) throws Exception {
        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");
//        String plantId = null;
//        if (token != null) {
//            plantId = userInfoDao.getUserFactory(StpUtil.getLoginIdByToken(token).toString()).getId();
//        }
        //        实体类
        List<Map<String, Object>> fields = jsonParam.getObject("fields", List.class);
//        文件名使用utf-8编码
        String filename = jsonParam.getString("filename");
//        数据
        List<Map<String, Object>> ids = jsonParam.getObject("ids", List.class);
//        是否有表头
        Boolean isHeader = jsonParam.getBoolean("isHeader");
//        mode为"current"时，导出当前页，为"all"时，导出所有页，selected时，导出选中数据
        String mode = jsonParam.getString("mode");
//        是否原始数据
        Boolean original = jsonParam.getBoolean("original");
//        分页
        Map<String, String> pager = jsonParam.getObject("pager", Map.class);
//        表格标题
        String sheetName = jsonParam.getString("sheetName");
        Map form = jsonParam.getObject("form", Map.class);

        String ordetailCo = null;
        if (form.get("ordetailCo") != null && !form.get("ordetailCo").equals("null")) {
            ordetailCo = form.get("ordetailCo").toString();
        }
        String startTime = null;
        if (form.get("startTime") != null && !form.get("startTime").equals("null")) {
            startTime = form.get("startTime").toString();
        }
        String endTime = null;
        if (form.get("endTime") != null && !form.get("endTime").equals("null")) {
            endTime = form.get("endTime").toString();
        }
        Future<List<BalanceEnquiryExcelEn>> listFuture = balanceEnquiryBu.balanceEnquiryExportExcel(fields, filename, ids, isHeader, mode, original, pager, sheetName, plantId, token, ordetailCo, startTime, endTime);
        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
        BorderStyle borderStyle = BorderStyle.THIN;
        short borderColor = IndexedColors.BLACK.getIndex();
        contentWriteCellStyle.setBorderTop(borderStyle);
        contentWriteCellStyle.setBorderBottom(borderStyle);
        contentWriteCellStyle.setBorderLeft(borderStyle);
        contentWriteCellStyle.setBorderRight(borderStyle);
        contentWriteCellStyle.setTopBorderColor(borderColor);
        contentWriteCellStyle.setBottomBorderColor(borderColor);
        contentWriteCellStyle.setLeftBorderColor(borderColor);
        contentWriteCellStyle.setRightBorderColor(borderColor);
        HorizontalCellStyleStrategy horizontalCellStyleStrategy =
                new HorizontalCellStyleStrategy(null, contentWriteCellStyle);
        List<BalanceEnquiryExcelEn> balanceEnquiryExcelEn = listFuture.get();
        response.setContentType("application/vnd.ms-excel; charset=utf-8");
        response.setCharacterEncoding("utf-8");
        if (filename == null || filename.equals("")) {
            filename = "余额查询";
        }
        response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8") + ".xlsx");
        EasyExcel.write(response.getOutputStream(), BalanceEnquiryExcelEn.class)
                .registerWriteHandler(horizontalCellStyleStrategy)
                .sheet("余额查询")
                .doWrite(balanceEnquiryExcelEn);
        response.getOutputStream().flush();
        response.getOutputStream().close();
    }


    //导出充值记录excel
    @PostMapping("/rechargeRecordExportExcel")
    public void rechargeRecordExportExcel(@RequestBody JSONObject jsonParam, HttpServletResponse response, HttpServletRequest request) throws Exception {
        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");
        //        实体类
        List<Map<String, Object>> fields = jsonParam.getObject("fields", List.class);
//        文件名使用utf-8编码
        String filename = jsonParam.getString("filename");
//        数据
        List<Map<String, Object>> ids = jsonParam.getObject("ids", List.class);
//        是否有表头
        Boolean isHeader = jsonParam.getBoolean("isHeader");
//        mode为"current"时，导出当前页，为"all"时，导出所有页，selected时，导出选中数据
        String mode = jsonParam.getString("mode");
//        是否原始数据
        Boolean original = jsonParam.getBoolean("original");
//        分页
        Map<String, String> pager = jsonParam.getObject("pager", Map.class);
//        表格标题
        String sheetName = jsonParam.getString("sheetName");
        Map form = jsonParam.getObject("form", Map.class);
//    String co, String startTime, String endTime
        String co = "", startTime = "", endTime = "";
        if (form != null) {
            if (form.get("co") != null) {
                co = form.get("co").toString();
            }
            if (form.get("startTime") != null) {
                startTime = form.get("startTime").toString();
            }
            if (form.get("endTime") != null) {
                endTime = form.get("endTime").toString();
            }
        }
        Future<List<RechargeRecordExcelEn>> listFuture = balanceEnquiryBu.rechargeRecordExportExcel(fields, filename, ids, isHeader, mode, original, pager, sheetName, token, co, startTime, endTime, plantId);
        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
        BorderStyle borderStyle = BorderStyle.THIN;
        short borderColor = IndexedColors.BLACK.getIndex();
        contentWriteCellStyle.setBorderTop(borderStyle);
        contentWriteCellStyle.setBorderBottom(borderStyle);
        contentWriteCellStyle.setBorderLeft(borderStyle);
        contentWriteCellStyle.setBorderRight(borderStyle);
        contentWriteCellStyle.setTopBorderColor(borderColor);
        contentWriteCellStyle.setBottomBorderColor(borderColor);
        contentWriteCellStyle.setLeftBorderColor(borderColor);
        contentWriteCellStyle.setRightBorderColor(borderColor);
        HorizontalCellStyleStrategy horizontalCellStyleStrategy =
                new HorizontalCellStyleStrategy(null, contentWriteCellStyle);
        List<RechargeRecordExcelEn> balanceEnquiryExcelEn = listFuture.get();
        response.setContentType("application/vnd.ms-excel; charset=utf-8");
        response.setCharacterEncoding("utf-8");
        if (filename == null || filename.equals("")) {
            filename = "充值记录";
        }
        response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8") + ".xlsx");
        EasyExcel.write(response.getOutputStream(), RechargeRecordExcelEn.class)
                .registerWriteHandler(horizontalCellStyleStrategy)
                .sheet("充值记录")
                .doWrite(balanceEnquiryExcelEn);
        response.getOutputStream().flush();
        response.getOutputStream().close();
    }


    /**
     * 查询授信
     */
    @GetMapping("/credit")
    public SzResult credit(@RequestParam(value = "ordetailId", required = false) String ordetailId, HttpServletRequest request) throws Exception {
        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");
    /*    if (!userInfoDao.getUserPermissionWeb(StpUtil.getLoginIdByToken(token).toString()).containsKey("addRechargeRecord")) {
            return SzResult.error("您没有新增充值记录的权限");
        }*/
        return balanceEnquiryBu.credit(ordetailId, token,plantId);
    }

    /**
     * 修改信用额度
     */
    @GetMapping("/updateCredit")
    @PermissionCheck("updateCredit")
    public SzResult updateCredit(@RequestParam String id, @RequestParam String credit, HttpServletRequest request) throws Exception {
        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");
        return balanceEnquiryBu.updateCredit(id, credit, token, plantId);
    }


}
